const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const db = require('../config/db.config.js');

exports.register = async (req, res) => {
  try {
    const { username, password, email, phone, role = 'user' } = req.body;

    // 检查用户是否已存在
    const [existingUsers] = await db.query(
      'SELECT * FROM Users WHERE username = ?',
      [username]
    );
    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const [result] = await db.query(
      'INSERT INTO Users (username, password, email, phone, role) VALUES (?, ?, ?, ?, ?)',
      [username, hashedPassword, email, phone, role]
    );

    res.status(201).json({ message: '注册成功', userId: result.insertId });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

exports.login = async (req, res) => {
  try {
    console.log('Login attempt:', req.body);
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({ message: '用户名和密码不能为空' });
    }

    // 查找用户
    console.log('Querying database for user:', username);
    const [users] = await db.query('SELECT * FROM Users WHERE username = ?', [
      username,
    ]);
    console.log('Database response:', users);

    if (users.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const user = users[0];
    console.log('Stored hashed password:', user.password);
    console.log('Input password:', password);

    console.log('Comparing passwords for user:', username);
    const isValidPassword = await bcrypt.compare(password, user.password);
    console.log('Password validation result:', isValidPassword);

    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 生成JWT
    console.log('Generating JWT token for user:', username);
    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
      },
    });
  } catch (error) {
    console.error('Login error details:', {
      error: error.message,
      stack: error.stack,
      body: req.body,
    });
    res.status(500).json({
      message: '服务器错误',
      details:
        process.env.NODE_ENV === 'development' ? error.message : undefined,
    });
  }
};

// 获取用户列表
exports.getUsers = async (req, res) => {
  try {
    const [users] = await db.query(
      'SELECT id, username, email,role FROM Users'
    );
    res.json(users);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单个用户信息
exports.getUser = async (req, res) => {
  try {
    const { id } = req.params;
    const [users] = await db.query(
      'SELECT id, username, email, role FROM Users WHERE id = ?',
      [id]
    );

    if (users[0]) {
      return res.status(404).json({ message: '未找到用户' });
    }

    res.json(users[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;

    // 开启事务
    await db.query('START TRANSACTION');

    try {
      // 删除用户相关的所有数据
      const tables = [
        'UserFavorites',
        'UserLikes',
        'UserCourses',
        'UserEvents',
      ];

      for (const table of tables) {
        try {
          await db.query(`DELETE FROM ${table} WHERE user_id = ?`, [id]);
        } catch (err) {
          // 忽略表不存在和字段不存在的错误
          if (
            err.code !== 'ER_NO_SUCH_TABLE' &&
            err.code !== 'ER_BAD_FIELD_ERROR'
          ) {
            throw err;
          }
        }
      }

      // 删除问诊服务记录
      await db.query(
        'DELETE FROM ConsultationServices WHERE consultation_id IN (SELECT id FROM Consultations WHERE username = (SELECT username FROM Users WHERE id = ?))',
        [id]
      );
      // 删除问诊记录
      await db.query(
        'DELETE FROM Consultations WHERE username = (SELECT username FROM Users WHERE id = ?)',
        [id]
      );

      // 最后删除用户
      await db.query('DELETE FROM Users WHERE id = ?', [id]);

      // 提交事务
      await db.query('COMMIT');

      res.json({ message: '用户删除成功' });
    } catch (error) {
      // 发生错误时回滚事务
      await db.query('ROLLBACK');
      throw error;
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取个人资料
exports.getProfile = async (req, res) => {
  try {
    const userId = req.user.id;
    const [users] = await db.query(
      'SELECT id, username, email, phone, role, avatar_url FROM Users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({ message: '未找到用户' });
    }

    res.json(users[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新个人资料
exports.updateProfile = async (req, res) => {
  try {
    const userId = req.user.id;
    const { email } = req.body;

    await db.query('UPDATE Users SET email = ? WHERE id = ?', [email, userId]);

    res.json({ message: '个人资料更新成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 修改密码
exports.changePassword = async (req, res) => {
  try {
    const userId = req.user.id;
    const { oldPassword, newPassword } = req.body;

    // 验证新密码长度
    if (newPassword.length < 6) {
      return res.status(400).json({ message: '新密码长度不能小于6位' });
    }

    // 获取用户当前密码
    const [users] = await db.query('SELECT password FROM Users WHERE id = ?', [
      userId,
    ]);

    if (users.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 验证旧密码
    const isValidPassword = await bcrypt.compare(
      oldPassword,
      users[0].password
    );
    if (!isValidPassword) {
      return res.status(400).json({ message: '旧密码不正确' });
    }

    // 加密新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await db.query('UPDATE Users SET password = ? WHERE id = ?', [
      hashedNewPassword,
      userId,
    ]);

    res.json({ message: '密码修改成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 上传头像
exports.uploadAvatar = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '请选择要上传的头像' });
    }

    const userId = req.user.id;
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;

    await db.query('UPDATE Users SET avatar_url = ? WHERE id = ?', [
      avatarUrl,
      userId,
    ]);

    res.json({
      message: '头像上传成功',
      avatar_url: avatarUrl,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取收藏历史
exports.getFavorites = async (req, res) => {
  try {
    const userId = req.user.id;
    const [favorites] = await db.query(
      `
      SELECT f.*, 
        CASE 
          WHEN f.content_type = 'course' THEN c.title
          WHEN f.content_type = 'event' THEN e.name
          WHEN f.content_type = 'knowledge' THEN k.title
        END as title,
        CASE 
          WHEN f.content_type = 'course' THEN c.description
          WHEN f.content_type = 'event' THEN e.description
          WHEN f.content_type = 'knowledge' THEN k.content
        END as description
      FROM Favorites f
      LEFT JOIN Courses c ON f.content_type = 'course' AND f.content_id = c.id
      LEFT JOIN Events e ON f.content_type = 'event' AND f.content_id = e.id
      LEFT JOIN Knowledge k ON f.content_type = 'knowledge' AND f.content_id = k.id
      WHERE f.user_id = ?
      ORDER BY f.created_at DESC
    `,
      [userId]
    );

    res.json(favorites);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取点赞历史
exports.getLikes = async (req, res) => {
  try {
    const userId = req.user.id;
    const [likes] = await db.query(
      `
      SELECT l.*, 
        CASE 
          WHEN l.content_type = 'course' THEN c.title
          WHEN l.content_type = 'event' THEN e.name
          WHEN l.content_type = 'knowledge' THEN k.title
        END as title,
        CASE 
          WHEN l.content_type = 'course' THEN c.description
          WHEN l.content_type = 'event' THEN e.description
          WHEN l.content_type = 'knowledge' THEN k.content
        END as description
      FROM Likes l
      LEFT JOIN Courses c ON l.content_type = 'course' AND l.content_id = c.id
      LEFT JOIN Events e ON l.content_type = 'event' AND l.content_id = e.id
      LEFT JOIN Knowledge k ON l.content_type = 'knowledge' AND l.content_id = k.id
      WHERE l.user_id = ?
      ORDER BY l.created_at DESC
    `,
      [userId]
    );

    res.json(likes);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};
